package com.atlassian.ldapuserimporter;

import com.opensymphony.util.TextUtils;

import javax.naming.directory.*;
import javax.naming.NamingException;
import javax.naming.NamingEnumeration;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;

/**
 * A little program to iterate through user nodes in an LDAP tree, and generate a Jelly script importing those users into JIRA.
 */
public class UserImporter {
    public static Properties props = new Properties();
    private static final String SEARCH_FOR = "searchfor";
    private static final String SEARCH_BASE = "searchbase";
    private static final String QUERY = "query";

    public static void main(String[] args) throws NamingException, IOException {
        File file = new File("ldap.properties");
        if (!file.exists()) {
            System.err.println("Please create a ldap.properties file in the current directory.");
            return;
        }

        if ( args.length > 0 && args[0].equals("?"))
        {
            System.out.println("Please use --listprops to list the current properties set in ldap.properties");
        }
        
        props.load(new FileInputStream("ldap.properties"));
        final String searchBase = (String) props.get("searchbase");
        final String query = (String) props.get("query");
        final String uidAttr = (String) props.get("username_attr");
        final String fullnameAttr = (String) props.get("fullname_attr");
        final String emailAttr = (String) props.get("email_attr");
        final String emailSuffix = (String) props.get("email_suffix");

        if ( args.length > 0 && args[0].equals("--listprops"))
        {
            props.list(System.out);
        }
        
        final boolean asService = props.get("jelly.service").toString().equals("1") && !props.get("jelly.username").toString().equals("") ;//&& !props.get("jelly.password").toString().equals("");

        DirContext ctx = new InitialDirContext(props);
        SearchControls ctls = new SearchControls();
        ctls.setReturningAttributes(new String[] {uidAttr, fullnameAttr, emailAttr});
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration results = ctx.search((searchBase), (query), ctls);
        System.out.println("<JiraJelly xmlns:jira=\"jelly:com.atlassian.jira.jelly.JiraTagLib\">");
        if ( asService ) {
//        	System.out.println("correr como servicio");
        	System.out.println("<jira:Login username=\"" + props.get("jelly.username") + "\" password=\"" + props.get("jelly.password") + "\">");
        }

        while (results != null && results.hasMore())
        {
            SearchResult sr = (SearchResult) results.next();
            Attribute uid = sr.getAttributes().get(uidAttr);
            if (uid == null) continue;
            String uidStr = (String) uid.get();

            Attribute fullname = null;
            String fullnameStr;
            if (fullnameAttr != null) {
                fullname = sr.getAttributes().get(fullnameAttr);
            }
            if (fullname != null) {
                fullnameStr = (String) fullname.get();
            } else {
                fullnameStr = uidStr;
            }

            Attribute email = null;
            String emailStr;
            if (emailAttr != null) {
                email = sr.getAttributes().get(emailAttr);
            }
            if (email != null) {
                emailStr = (String) email.get();
            } else {
                emailStr = uidStr.replace(' ', '_')+emailSuffix;
            }

            String passwordStr = uidStr;
            System.out.println("\t<jira:CreateUser username=\""+TextUtils.htmlEncode(uidStr).toLowerCase()+"\" password=\""+TextUtils.htmlEncode(passwordStr)+"\" confirm=\""+TextUtils.htmlEncode(passwordStr)+"\" fullname=\""+TextUtils.htmlEncode(fullnameStr)+"\" email=\""+TextUtils.htmlEncode(emailStr)+"\"/>");
        }
        
        if (asService) {
        	System.out.println("</jira:Login>");
        }
        System.out.println("</JiraJelly>");

    }
}
